package product;


import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale.Category;

import javax.swing.JPanel;

import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class BarChart extends JInternalFrame
{
	Connection con;
	private JMenuBar menuBar;
	private JButton searchBtn;
	int dept1;
	int dept2;
	String dept;
	ProductMain2 pm;
	DefaultCategoryDataset defaultcategorydataset=new DefaultCategoryDataset();
	String str; 
	private static JComboBox monthnum;
	private static JComboBox yearnum;
	private static JComboBox monthnum2;
	private static JComboBox yearnum2;
	private JLabel lblNewLabel;
	private JPanel panel_3;
	boolean tflag=false;
	private JPanel panel_5;
	private JPanel panel;
	private JPanel panel_6;
	private JPanel panel_7;
	private JTextField findStr;
	private JButton btnNewButton;
	SearchPro sc;
	Date nal;
	String m;
	String y;
	SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
    public BarChart(ProductMain2 p,Connection c) throws Exception
    {
    	super("기간별막대그래프", true, true, true,true);
    	addInternalFrameListener(new InternalFrameAdapter() {
    		@Override
    		public void internalFrameClosing(InternalFrameEvent e) {
    		
    				pm.bc = null;
    		}
    	});
    	this.pm=p;
    	this.con=c;
        CategoryDataset categorydataset = createDataset();
        JFreeChart jfreechart = createChart(categorydataset);
        setJMenuBar(getMenuBar_1());
        ChartPanel chartpanel = new ChartPanel(jfreechart);
        chartpanel.setPreferredSize(new Dimension(500, 270));
        setContentPane(chartpanel);
        chartpanel.setLayout(null);
        nal=new Date();
//        System.out.println(sd.format(nal));
        y=sd.format(nal).substring(0, 4);
        m=sd.format(nal).substring(5,7);
//        System.out.println(m);
//        System.out.println(y);
        yearnum.setSelectedItem(y);
    	monthnum.setSelectedItem(m);
    	yearnum2.setSelectedItem(y);
    	monthnum2.setSelectedItem(m);
    }
    public void DbCon()throws Exception{
		 Class.forName("oracle.jdbc.driver.OracleDriver");
		 System.out.println("드라이버 로딩 성공...");
	      String url="jdbc:oracle:thin:@192.168.10.4:1521:XE";
	        
	      String user="hr";
	      String pwd="hr";
	        
	     con=DriverManager.getConnection(url,user,pwd);
	      System.out.println("DB 연결 성공!");
	}
	public void setData(String s){
		findStr.setText(s);		
	}
    private CategoryDataset createDataset() throws Exception{
		
		DbCon();
//		 DefaultCategoryDataset defaultcategorydataset=new DefaultCategoryDataset();
	if(tflag==false){
		 defaultcategorydataset.addValue(0,"","");
		  JFreeChart jfreechart = ChartFactory.createBarChart("Bar Chart Demo", "Category", "Volum Of Stock", null, PlotOrientation.VERTICAL, true, true, false);
	        jfreechart.setBackgroundPaint(Color.white);
	        CategoryPlot categoryplot = jfreechart.getCategoryPlot();
	        categoryplot.setBackgroundPaint(Color.lightGray);
	        categoryplot.setDomainGridlinePaint(Color.white);
	        categoryplot.setDomainGridlinesVisible(true);
	        categoryplot.setRangeGridlinePaint(Color.white);
	        NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
	        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
	        BarRenderer barrenderer = (BarRenderer)categoryplot.getRenderer();
	        barrenderer.setDrawBarOutline(false);
	        GradientPaint gradientpaint = new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 64));
	        GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 64, 0));
	        GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0));
	        barrenderer.setSeriesPaint(0, gradientpaint);
	        barrenderer.setSeriesPaint(1, gradientpaint1);
	        barrenderer.setSeriesPaint(2, gradientpaint2);
	        CategoryAxis categoryaxis = categoryplot.getDomainAxis();
	        categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.52359877559829882D));
	      
	}
	else{
		String pm="";
		String pm2="";
		String sm="";
		String sm2="";
	
		
			String year1=yearnum.getSelectedItem()+""+monthnum.getSelectedItem()+"";
			String year2=yearnum2.getSelectedItem()+""+monthnum2.getSelectedItem()+"";

			int num1=Integer.parseInt(year1);
			int num2=Integer.parseInt(year2);
			str = findStr.getText();
			Statement st=con.createStatement();
		for(int i = num1 ; i<num2+1; i++){
			dept1=0;
			dept2=0;
			String sql1 = " select sa_pro_code, nvl(sum(sa_ea),0) from sale where to_char(sa_reg_date,'yyyymm')=? "
					+ "group by sa_pro_code";
			PreparedStatement pstmt1 = con.prepareStatement(sql1);
			pstmt1.setInt(1, i);
			ResultSet rs1=pstmt1.executeQuery();
			while(rs1.next()){
				if(rs1.getString(1).equals(str)){
					if(rs1.getString(2)==null){
						dept1=0;
					}else{
					dept1 = Integer.parseInt(rs1.getString(2));
					}
				}
			}    	  

			String sql2 = " select code, nvl(sum(ea),0) from product where to_char(nal,'yyyymm') = ?"
					+ " group by code";
			PreparedStatement pstmt2 = con.prepareStatement(sql2);
			pstmt2.setInt(1, i);
			ResultSet rs2=pstmt2.executeQuery();
			while(rs2.next()){
				if(rs2.getString(1).equals(str)){
					if(rs2.getString(2)==null){
						dept2=0;
					}else{
						dept=rs2.getString(1);
						dept2 = Integer.parseInt(rs2.getString(2));
					}
				}
			}
			
			String ab = Integer.toString(i).substring(0,4);
			String ab1 = Integer.toString(i).substring(4, 6);
			String Day = ab+"-"+ab1;

			defaultcategorydataset.addValue(dept2-dept1,str,Day);//재고량,코드,

		}
	}
	con.close();
		return defaultcategorydataset;
	}

    private JFreeChart createChart(CategoryDataset categorydataset)
    {

        JFreeChart jfreechart = ChartFactory.createBarChart("Bar Chart", "제품 코드", "재고량", categorydataset, PlotOrientation.VERTICAL, true, true, false);
        jfreechart.setBackgroundPaint(Color.white);
        CategoryPlot categoryplot = jfreechart.getCategoryPlot();
        categoryplot.setBackgroundPaint(Color.lightGray);
        categoryplot.setDomainGridlinePaint(Color.white);
        categoryplot.setDomainGridlinesVisible(true);
        categoryplot.setRangeGridlinePaint(Color.white);
        NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        BarRenderer barrenderer = (BarRenderer)categoryplot.getRenderer();
        barrenderer.setDrawBarOutline(false);
        GradientPaint gradientpaint = new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 64));
        GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 64, 0));
        GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0));
        barrenderer.setSeriesPaint(0, gradientpaint);
        barrenderer.setSeriesPaint(1, gradientpaint1);
        barrenderer.setSeriesPaint(2, gradientpaint2);
        CategoryAxis categoryaxis = categoryplot.getDomainAxis();
        categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.52359877559829882D));
        TextTitle title = jfreechart.getTitle();
        title.setFont(new Font("굴림", 0, 20));
        CategoryAxis titleX =categoryplot.getDomainAxis();
        titleX.setLabelFont(new Font("돋움",0,15));
        
        ValueAxis titleY =categoryplot.getRangeAxis();
        titleY.setLabelFont(new Font("돋움",0,15));
        jfreechart.getLegend().setItemFont(new Font("돋움",Font.PLAIN,15));
        return jfreechart;
    }

    public JPanel createDemoPanel() throws Exception
    {
        JFreeChart jfreechart = createChart(createDataset());
        return new ChartPanel(jfreechart);
    }

    public static String getDemoDescription()
    {
        return "A bar chart.";
    }

//    public static void main(String args[]) throws Exception
//    {
//        BarChart barchartdemo1 = new BarChart();
//        barchartdemo1.pack();
//        RefineryUtilities.centerFrameOnScreen(barchartdemo1);
//        barchartdemo1.setVisible(true);
//        
//    }
	private JMenuBar getMenuBar_1() {
		if (menuBar == null) {
			menuBar = new JMenuBar();
			menuBar.add(getPanel_5());
			menuBar.add(getSearchBtn());
			menuBar.add(getBtnNewButton());
		}
		return menuBar;
	}
	private JButton getSearchBtn() {
		if (searchBtn == null) {
			searchBtn = new JButton("검색");
			searchBtn.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						if(findStr.getText().equals("")){
							JOptionPane.showMessageDialog(null,"제품코드를 입력해주세요.");
						}
						else{
						tflag=true;
						CategoryDataset categorydataset = createDataset();
				        JFreeChart jfreechart = createChart(categorydataset);
				        setJMenuBar(getMenuBar_1());
				        ChartPanel chartpanel = new ChartPanel(jfreechart);
				        chartpanel.setPreferredSize(new Dimension(500, 270));
				        setContentPane(chartpanel);
				        chartpanel.setLayout(null);
				        chartpanel.updateUI();
						}
					}catch(Exception ex){
						ex.printStackTrace();
					}
				}
			});
		}
		return searchBtn;
	}
	private JComboBox getMonthnum() {
		if (monthnum == null) {
			monthnum = new JComboBox();
			monthnum.setPreferredSize(new Dimension(50, 21));
			monthnum.setModel(new DefaultComboBoxModel(new String[] {"", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
		}
		return monthnum;
	}
	private JComboBox getYearnum() {
		if (yearnum == null) {
			yearnum = new JComboBox();
			yearnum.setPreferredSize(new Dimension(65, 21));
			yearnum.setModel(new DefaultComboBoxModel(new String[] {"2014"}));
		}
		return yearnum;
	}
	private JComboBox getMonthnum2() {
		if (monthnum2 == null) {
			monthnum2 = new JComboBox();
			monthnum2.setPreferredSize(new Dimension(50, 21));
			monthnum2.setModel(new DefaultComboBoxModel(new String[] {m, "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
			
			}
		return monthnum2;
	}
	private JComboBox getYearnum2() {
		if (yearnum2 == null) {
			yearnum2 = new JComboBox();
			yearnum2.setPreferredSize(new Dimension(65, 21));
			yearnum2.setModel(new DefaultComboBoxModel(new String[] {"2014"}));
		}
		return yearnum2;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel(" ~ ");
		}
		return lblNewLabel;
	}
	private JPanel getPanel_3_1() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(new BorderLayout(0, 0));
		}
		return panel_3;
	}
	private JPanel getPanel_5() {
		if (panel_5 == null) {
			panel_5 = new JPanel();
			panel_5.setLayout(new BorderLayout(0, 0));
			panel_5.add(getPanel(), BorderLayout.WEST);
			panel_5.add(getPanel_6(), BorderLayout.CENTER);
			panel_5.add(getPanel_7(), BorderLayout.EAST);
			panel_5.add(getPanel_3_1(), BorderLayout.NORTH);
		}
		return panel_5;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getYearnum(), BorderLayout.WEST);
			panel.add(getMonthnum(), BorderLayout.CENTER);
			panel.add(getLblNewLabel(), BorderLayout.EAST);
		}
		return panel;
	}
	private JPanel getPanel_6() {
		if (panel_6 == null) {
			panel_6 = new JPanel();
			panel_6.setLayout(new BorderLayout(0, 0));
			panel_6.add(getYearnum2());
			panel_6.add(getMonthnum2(), BorderLayout.EAST);
		}
		return panel_6;
	}
	private JPanel getPanel_7() {
		if (panel_7 == null) {
			panel_7 = new JPanel();
			panel_7.setPreferredSize(new Dimension(100, 10));
			panel_7.setLayout(new BorderLayout(0, 0));
			panel_7.add(getFindStr(), BorderLayout.CENTER);
		}
		return panel_7;
	}
	private JTextField getFindStr() {
		if (findStr == null) {
			findStr = new JTextField();
			findStr.setPreferredSize(new Dimension(6, 10));
			findStr.setColumns(5);
		}
		return findStr;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("제품조회");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
					SearchPro sc=new SearchPro(pm);
					sc.setBounds(618, 213, 150, 398);
					sc.setAlwaysOnTop(true);
					sc.setVisible(true);
					}catch(Exception ex){
						ex.printStackTrace();
					}
				}
			});
		}
		return btnNewButton;
	}
}


